<?php

namespace app\api\controller;

use addons\qrcode\library\Service;
use app\common\controller\Api;
use app\common\model\ActivityOrder;
use app\common\model\ActivityTemplate;
use app\common\model\Activity as M;
use think\Image;

/**
 * Token接口
 */
class Activity extends Api
{
    protected $noNeedLogin = ['getActivity', 'saveActivity', 'saveDraft'];
    protected $noNeedRight = '*';

    public function getActivity()
    {
        $id = input('id');
        $model = new M();
        $info = $model->where('id', $id)->find();

        if (empty($info)) {
            $this->error('活动不存在');
        }

        $info['user_list'] = [];
        if ($info['in_set'] == 1) {
            // 获取参与活动的前6名
            $orderModel = new ActivityOrder();
            $orderList = $orderModel
                ->where('activity_id', $id)
                ->where('pay_status', 2)
                ->order('id desc')
                ->limit(6)
                ->group('buy_id')
                ->column('buy_id');


            $userModel = new \app\common\model\User();
            $userList = $userModel->where('id', 'in', $orderList)->column('id,avatar,nickname');
            if ($userList) {
                foreach ($userList as &$v) {
                    if ($v['avatar']) {
                        $v['avatar'] = cdnurl($v['avatar'], true);
                    } else {
                        $v['avatar'] = letter_avatar($v['nickname']);
                    }
                }
                $info['user_list'] = array_values($userList);
            }
        }

        $this->success('success', $info);
    }

    public function saveDraft()
    {
        $data = $this->request->post(false);
        $id = $this->request->get('id');

        if (empty($data['title'])) {
            $this->error('活动名称不能为空');
        }

        if (isset($data['start_time']) and isset($data['end_time']) and !empty($data['start_time']) and !empty($data['end_time'])) {
            if (strtotime($data['start_time']) >= strtotime($data['end_time'])) {
                $this->error('结束时间必须大于开始时间');
            }
        }


        if (isset($data['phone']) and !empty($data['phone'])) {
            // 验证手机号
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $data['phone'])) {
                $this->error('手机号格式不正确');
            }
        }

        if (isset($data['start_time']) and !empty($data['start_time'])) {
            $data['start_time'] = strtotime($data['start_time']);
        }
        if (isset($data['end_time']) and !empty($data['end_time'])) {
            $data['end_time'] = strtotime($data['end_time']);
        }

        $data['is_completed_edit'] = 0;

        $model = new M();

        if (empty($id)) {
            $data['user_id'] = $this->auth->id;
            $res = $model->allowField(true)->save($data);
        } else if (is_numeric($id) and $id > 0) {
            $res = $model->allowField(true)->save($data, ['id' => $id]);
        }

        if ($res) {
            $this->success('草稿保存成功');
        } else {
            $this->error('草稿保存失败');
        }

    }

    public function saveActivity()
    {
        $data = $this->request->post(false);
        $id = $this->request->get('id');

        if (empty($data['title'])) {
            $this->error('活动名称不能为空');
        }

        if (empty($data['start_time'])) {
            $this->error('开始时间不能为空');
        }

        if (empty($data['end_time'])) {
            $this->error('结束时间不能为空');
        }

        if (strtotime($data['start_time']) >= strtotime($data['end_time'])) {
            $this->error('结束时间必须大于开始时间');
        }

        if (empty($data['phone'])) {
            $this->error('联系电话不能为空');
        }

        // 验证手机号
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $data['phone'])) {
            $this->error('手机号格式不正确');
        }

        if (empty($data['address'])) {
            $this->error('活动地址不能为空');
        }

        //活动标题图可以为空
//        if (empty($data['images'])) {
//            $this->error('活动标题图不能为空');
//        }

        if (0 == $data['templateid'] and empty($data['template_custom_image'])) {
            $this->error('当自定义模板时，模板图不能为空');
        }

        if (empty($data['share_image'])) {
            $this->error('顶部图不可为空');
        }

        if (empty($data['share_title'])) {
            $this->error('活动分享摘要不可为空');
        }

        if (empty($data['content_node'])) {
            $this->error('内容不可为空');
        }

        if (empty($data['share_back_image'])) {
            $this->error('分享背景图不可为空');
        }

        if (empty($data['share_back_image'])) {
            $this->error('分享背景图不可为空');
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        $model = new M();

        $data['is_completed_edit'] = 1;

        if (empty($id)) {
            $data['user_id'] = $this->auth->id;
            $res = $model->allowField(true)->save($data);
        } else if (is_numeric($id) and $id > 0) {
            $res = $model->allowField(true)->save($data, ['id' => $id]);
        }

        if ($res) {
            $this->success('提交成功');
        } else {
            $this->error('提交失败');
        }
    }

    public function getActivityList()
    {
        $model = new M();
        $list = $model->where('user_id', $this->auth->id)->order('id desc')->select();

        if ($list) {
            $arr = [];
            foreach ($list as $v) {
                $arr[$v['id']] = $v['id'];
            }

            $orderModel = new ActivityOrder();
            $orderList = $orderModel
                ->field('activity_id,count(*) c')
                ->where('activity_id', 'in', $arr)
                ->where('pay_status', 2)
                ->group('activity_id')
                ->select();

            $order = [];
            foreach ($orderList as $v) {
                $order[$v['activity_id']] = $v['c'];
            }

            foreach ($list as &$v) {
                $v['order_count'] = $order[$v['id']] ?? 0;
            }
        }

        $this->success('success', $list);
    }

    public function getShopNameList()
    {
        $user_id = $this->auth->id;
        $model = new M();
        $list = $model->field('id,title,createtime')
//            ->where('status', 1)
            ->where('user_id', $user_id)
            ->order('id desc')->select();

        $this->success('success', $list);
    }

    public function setStatus()
    {
        $id = input('post.id');

        $model = new M();
        $info = $model->where('id', $id)->where('user_id', $this->auth->id)->find();

        if (empty($info)) {
            $this->error('活动不存在');
        }

        if (1 == $info->status) { // 下线无所谓
            $res = $model->allowField(true)->save(['status' => $info['status'] == 1 ? 0 : 1], ['id' => $id]);
        } else if (0 == $info->status) {
            if (0 == $info->is_completed_edit) {
                $this->error('活动内容不完整, 不能上线');
            }
            $res = $model->allowField(true)->save(['status' => $info['status'] == 1 ? 0 : 1], ['id' => $id]);
        }

        if ($res) {
            $this->success('提交成功');
        } else {
            $this->error('提交失败');
        }
    }

    // 删除
    public function setDel()
    {
        $id = input('post.id');

        $model = new M();
        $info = $model->where('id', $id)->where('user_id', $this->auth->id)->find();

        if (empty($info)) {
            $this->error('活动不存在');
        }

        $orderModel = new ActivityOrder();
        $orderInfo = $orderModel->where('activity_id', $id)->count();
        if ($orderInfo) {
            $this->error('活动已有订单，不可删除');
        }

        $res = $model->where('id', $id)->delete();

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    // 生成图片二维码
    public function createQrcode()
    {
        $id = input('post.id');
        $model = new M();
        $info = $model->where('id', $id)->find();

        if (empty($info)) {
            $this->error('活动不存在');
        }

        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $domain = $_SERVER['HTTP_HOST'];

        $url = "$protocol://$domain" . '/pages/activity/info?user_id=' . $this->auth->id . '&id=' . $id;

        // 生成二维码
        $qrCode = Service::qrcode([
            'text' => $url,
            'size' => 176,
            'padding' => 0,
            'foreground' => '#000000',
            'background' => '#ffffff',
            'logo' => false,
        ]);

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        $fileName = $this->auth->id . '_' . $id . '.png';
        $filePath = $qrcodePath . $fileName;
        if (is_really_writable($qrcodePath)) {
            $qrCode->writeFile($filePath);
        }

//        print_r($info['share_image']);
        // 合成图片
        $share_image = Image::open(ROOT_PATH . 'public' . $info['share_back_image']);

        $share_image->water($filePath, ['366', '510'])->save($filePath);
        $this->success('success', ['qrcode' => cdnurl('/uploads/qrcode/' . $fileName . '?' . time() . rand(100000, 999999), true)]);
    }

}
